﻿using OpenTK.Graphics.OpenGL4;

namespace TrinityEngine
{
    public class StreamVertexBuffer : IDisposable
    {
        private bool _disposed = false;

        private readonly int _rendererID;

        private int _bufferSize;

        public StreamVertexBuffer(int bufferSize)
        {
            _bufferSize = bufferSize;
            _rendererID = GL.GenBuffer();
            GL.BindBuffer(BufferTarget.ArrayBuffer, _rendererID);
            GL.BufferData(BufferTarget.ArrayBuffer, _bufferSize, IntPtr.Zero, BufferUsageHint.StreamDraw);
        }

        public void SetData(float[] data)
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, _rendererID);
            GL.BufferSubData(BufferTarget.ArrayBuffer, IntPtr.Zero, data.Length * sizeof(float), data);
        }

        ~StreamVertexBuffer()
        {
            Dispose(false);
        }

        public void Bind()
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, _rendererID);
        }

        public void Unbind()
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            if (disposing)
            {

            }

            GL.DeleteBuffer(_rendererID);

            _disposed = true;
        }
    }
}
